// 敌人系统 - 管理敌人生成、AI和Boss逻辑
class EnemySystem {
    constructor(scene) {
        this.scene = scene;
    }

    getRandomEnemyType(wave) {
        const enemyTypes = [
            {
                name: 'normal',
                sprite: 'enemy',
                health: 20,
                speed: 50,
                damage: 10
            },
            {
                name: 'fast',
                sprite: 'fast_enemy',
                health: 10,
                speed: 100,
                damage: 8
            },
            {
                name: 'tank',
                sprite: 'tank_enemy',
                health: 60,
                speed: 25,
                damage: 15
            }
        ];

        // 根据波次调整敌人类型概率
        let weights = [60, 25, 15]; // 普通, 快速, 坦克
        if (wave > 3) weights = [40, 35, 25];
        if (wave > 7) weights = [30, 30, 40];

        const random = Math.random() * 100;
        let cumulative = 0;

        for (let i = 0; i < weights.length; i++) {
            cumulative += weights[i];
            if (random <= cumulative) {
                return enemyTypes[i];
            }
        }

        return enemyTypes[0];
    }

    spawnEnemy(wave) {
        // 检查是否为Boss波次 (每5波)
        if (wave % 5 === 0 && !this.scene.isBossWave && !this.scene.currentBoss) {
            this.spawnBoss(wave);
            return;
        }

        // 普通敌人生成 - 在玩家附近生成
        if (!this.scene.isBossWave) {
            const side = Phaser.Math.Between(0, 3);
            let x, y;
            
            // 在玩家附近的屏幕边缘生成敌人，确保能看到
            const camera = this.scene.cameras.main;
            const playerX = this.scene.player.x;
            const playerY = this.scene.player.y;
            const spawnDistance = 400; // 距离玩家400像素生成

            switch (side) {
                case 0: // 上
                    x = playerX + Phaser.Math.Between(-300, 300);
                    y = playerY - spawnDistance;
                    break;
                case 1: // 右
                    x = playerX + spawnDistance;
                    y = playerY + Phaser.Math.Between(-300, 300);
                    break;
                case 2: // 下
                    x = playerX + Phaser.Math.Between(-300, 300);
                    y = playerY + spawnDistance;
                    break;
                case 3: // 左
                    x = playerX - spawnDistance;
                    y = playerY + Phaser.Math.Between(-300, 300);
                    break;
            }

            // 确保敌人不会在墙体内生成
            const wallThickness = 32;
            x = Phaser.Math.Clamp(x, wallThickness + 20, 2400 - wallThickness - 20);
            y = Phaser.Math.Clamp(y, wallThickness + 20, 1800 - wallThickness - 20);

            // 随机生成不同类型的敌人
            const enemyType = this.getRandomEnemyType(wave);
            const enemy = this.scene.enemies.create(x, y, enemyType.sprite);

            // 设置敌人属性
            enemy.health = enemyType.health + (wave * 3);
            enemy.maxHealth = enemy.health;
            enemy.speed = enemyType.speed;
            enemy.damage = enemyType.damage;
            enemy.type = enemyType.name;
            enemy.lastFired = 0;



            // 为敌人添加血条
            this.createEnemyHealthBar(enemy);
            
            // 调试信息 - 在控制台显示敌人生成位置
            console.log(`Enemy spawned at (${x}, ${y}), Player at (${playerX}, ${playerY})`);
        }
    }

    spawnBoss(wave) {
        // 设置Boss状态
        this.scene.isBossWave = true;
        console.log(`生成Boss，波次: ${wave}`);

        // 计算Boss生成位置（在玩家周围一定距离）
        const spawnDistance = 500;
        const angle = Math.random() * Math.PI * 2;
        const spawnX = this.scene.player.x + Math.cos(angle) * spawnDistance;
        const spawnY = this.scene.player.y + Math.sin(angle) * spawnDistance;

        // 创建Boss
        const boss = this.scene.enemies.create(spawnX, spawnY, 'boss_enemy');
        boss.setScale(2);
        boss.type = 'boss';
        
        // 根据波数增加Boss属性
        const baseHealth = 1000;
        const healthMultiplier = 1 + (wave - 5) * 0.2; // 每5波增加20%生命值
        boss.maxHealth = Math.floor(baseHealth * healthMultiplier);
        boss.health = boss.maxHealth;
        boss.damage = 50 + wave * 2;
        boss.speed = 80;
        boss.lastFired = 0;
        boss.bulletSpeed = 250;
        boss.fireRate = 800; // Boss射击间隔（毫秒）
        boss.burstCount = 0; // 连发计数
        boss.burstMode = false; // 是否在连发模式

        // 设置Boss的物理属性
        boss.setCollideWorldBounds(true);
        boss.setBounce(1);

        // 创建Boss血条
        this.createBossHealthBar(boss);

        // 保存Boss引用
        this.scene.currentBoss = boss;

        // 暂停普通敌人生成
        this.scene.spawnEnemyTimer.paused = true;

        // 显示Boss出现文本
        EffectSystem.showFloatingText(this.scene, boss.x, boss.y - 50, "Boss出现！", '#ff0000');
    }

    updateEnemies() {
        // 检查并移除超出边界的敌人
        const worldBounds = {
            left: 0,
            right: 2400,
            top: 0,
            bottom: 1800
        };

        // 检查当前Boss状态
        let foundBoss = false;

        this.scene.enemies.children.entries.forEach(enemy => {
            // 检查敌人是否超出边界或无效
            if (!enemy.active || !enemy.body ||
                enemy.x < worldBounds.left || enemy.x > worldBounds.right ||
                enemy.y < worldBounds.top || enemy.y > worldBounds.bottom) {
                
                // 如果是Boss，清理所有相关UI并重置状态
                if (enemy.type === 'boss') {
                    console.log('Boss被移除，位置:', enemy.x, enemy.y, '血量:', enemy.health);
                    if (enemy.bossHealthBg) enemy.bossHealthBg.destroy();
                    if (enemy.bossHealthFg) enemy.bossHealthFg.destroy();
                    if (enemy.bossText) enemy.bossText.destroy();
                    if (enemy.indicator) enemy.indicator.destroy();
                    if (enemy.distanceText) enemy.distanceText.destroy();
                    if (enemy.bossIndicatorText) enemy.bossIndicatorText.destroy();
                    
                    // 重置Boss状态
                    this.scene.isBossWave = false;
                    this.scene.currentBoss = null;
                    
                    // 恢复敌人生成
                    if (this.scene.spawnEnemyTimer) {
                        this.scene.spawnEnemyTimer.paused = false;
                        console.log('恢复敌人生成');
                    }
                }
                
                // 清理普通敌人的血条
                if (enemy.healthBar) {
                    enemy.healthBar.destroy();
                    enemy.healthBarBg.destroy();
                }
                
                enemy.destroy();
                return;
            }

            // 记录找到的Boss
            if (enemy.type === 'boss') {
                foundBoss = true;
                if (this.scene.currentBoss !== enemy) {
                    this.scene.currentBoss = enemy;
                }
            }

            if (enemy.type === 'boss') {
                this.updateBoss(enemy);
            } else {
                this.updateNormalEnemy(enemy);
            }

            // 更新敌人血条位置
            if (enemy.healthBar) {
                enemy.healthBar.x = enemy.x - 10;
                enemy.healthBar.y = enemy.y - 20;
                enemy.healthBarBg.x = enemy.x - 10;
                enemy.healthBarBg.y = enemy.y - 20;

                // 更新血条长度
                const healthPercent = enemy.health / enemy.maxHealth;
                enemy.healthBar.scaleX = healthPercent;
            }
        });

        // 如果没有找到Boss但状态显示有Boss，重置状态
        if (!foundBoss && (this.scene.isBossWave || this.scene.currentBoss)) {
            console.log('未找到Boss，重置状态');
            this.scene.isBossWave = false;
            this.scene.currentBoss = null;
            if (this.scene.spawnEnemyTimer) {
                this.scene.spawnEnemyTimer.paused = false;
                console.log('恢复敌人生成');
            }
        }

        // 清理敌人子弹
        this.scene.enemyBullets.children.entries.forEach(bullet => {
            if (!bullet.active || !bullet.body ||
                bullet.x < worldBounds.left || bullet.x > worldBounds.right ||
                bullet.y < worldBounds.top || bullet.y > worldBounds.bottom) {
                bullet.destroy();
            }
        });
    }

    updateNormalEnemy(enemy) {
        // 普通敌人朝玩家移动
        const angle = Phaser.Math.Angle.Between(
            enemy.x, enemy.y,
            this.scene.player.x, this.scene.player.y
        );

        const speed = enemy.speed + (this.scene.wave * 3);
        enemy.setVelocity(
            Math.cos(angle) * speed,
            Math.sin(angle) * speed
        );
    }

    updateBoss(boss) {
        if (!boss || !boss.active) return;

        // 更新Boss AI
        const distanceToPlayer = Phaser.Math.Distance.Between(
            boss.x, boss.y,
            this.scene.player.x, this.scene.player.y
        );

        // Boss行为模式
        if (distanceToPlayer > 300) {
            // 追击玩家
            const angle = Phaser.Math.Angle.Between(
                boss.x, boss.y,
                this.scene.player.x, this.scene.player.y
            );

            boss.setVelocity(
                Math.cos(angle) * boss.speed,
                Math.sin(angle) * boss.speed
            );

            // Boss弹幕攻击系统
            this.updateBossAttack(boss);
        } else {
            // 在玩家附近时，进行冲刺攻击
            if (!boss.isCharging && Math.random() < 0.01) {
                boss.isCharging = true;
                const chargeAngle = Phaser.Math.Angle.Between(
                    boss.x, boss.y,
                    this.scene.player.x, this.scene.player.y
                );

                boss.setVelocity(
                    Math.cos(chargeAngle) * boss.speed * 3,
                    Math.sin(chargeAngle) * boss.speed * 3
                );

                // 冲刺结束后恢复正常移动
                this.scene.time.delayedCall(1000, () => {
                    if (boss && boss.active) {
                        boss.isCharging = false;
                    }
                });
            }
        }

        // 更新Boss血条位置
        if (boss.healthBar) {
            boss.healthBar.x = boss.x;
            boss.healthBar.y = boss.y - 40;
            boss.healthBarBg.x = boss.x;
            boss.healthBarBg.y = boss.y - 40;
        }

        // 更新Boss UI - 确保传递正确的波次信息
        if (this.scene.uiSystem && boss.active) {
            this.scene.uiSystem.updateBossUI(boss, boss.wave || this.scene.wave);
        }
    }
    
    updateBossIndicator(boss) {
        // 获取相机和游戏尺寸
        const camera = this.scene.cameras.main;
        const gameWidth = this.scene.game.config.width;
        const gameHeight = this.scene.game.config.height;
        
        // 计算Boss相对于相机的位置
        const bossCamX = boss.x - camera.scrollX;
        const bossCamY = boss.y - camera.scrollY;
        
        // 检查Boss是否在视口内
        const inView = (
            bossCamX > 0 && 
            bossCamX < gameWidth && 
            bossCamY > 0 && 
            bossCamY < gameHeight
        );
        
        // 如果Boss不在视口内，显示指示器
        if (!inView) {
            // 如果指示器不存在，创建它
            if (!boss.indicator) {
                // 创建更大更明显的三角形指示器
                const indicatorGraphics = this.scene.add.graphics();
                indicatorGraphics.fillStyle(0xff0000, 1);
                indicatorGraphics.lineStyle(3, 0xffffff, 1);
                indicatorGraphics.beginPath();
                indicatorGraphics.moveTo(0, -20);
                indicatorGraphics.lineTo(15, 10);
                indicatorGraphics.lineTo(-15, 10);
                indicatorGraphics.closePath();
                indicatorGraphics.fillPath();
                indicatorGraphics.strokePath();
                
                // 将图形转换为纹理
                indicatorGraphics.generateTexture('boss_indicator', 30, 30);
                indicatorGraphics.destroy();
                
                // 创建指示器精灵 - 更大更明显
                boss.indicator = this.scene.add.sprite(0, 0, 'boss_indicator')
                    .setScrollFactor(0)
                    .setDepth(10000) // 超高深度值确保显示在最顶层
                    .setScale(1.5);
                
                // 添加闪烁和脉冲动画
                this.scene.tweens.add({
                    targets: boss.indicator,
                    alpha: 0.7,
                    duration: 300,
                    yoyo: true,
                    repeat: -1
                });
                
                this.scene.tweens.add({
                    targets: boss.indicator,
                    scale: 1.8,
                    duration: 500,
                    yoyo: true,
                    repeat: -1
                });
            }
            
            // 计算指示器位置
            const angle = Phaser.Math.Angle.Between(
                camera.scrollX + gameWidth/2, 
                camera.scrollY + gameHeight/2,
                boss.x, boss.y
            );
            
            // 计算指示器在屏幕边缘的位置
            const padding = 60; // 距离屏幕边缘的距离
            let indicatorX = gameWidth/2 + Math.cos(angle) * (gameWidth/2 - padding);
            let indicatorY = gameHeight/2 + Math.sin(angle) * (gameHeight/2 - padding);
            
            // 设置指示器位置和旋转
            boss.indicator.setPosition(indicatorX, indicatorY);
            boss.indicator.setRotation(angle + Math.PI/2); // 让箭头指向Boss
            boss.indicator.setVisible(true);
            
            // 添加距离文本
            if (!boss.distanceText) {
                boss.distanceText = this.scene.add.text(0, 0, '', {
                    fontSize: '16px',
                    fontStyle: 'bold',
                    fill: '#ff0000',
                    stroke: '#000000',
                    strokeThickness: 3
                }).setOrigin(0.5)
                  .setScrollFactor(0)
                  .setDepth(10000);
            }
            
            // 计算并显示距离
            const distance = Math.floor(Phaser.Math.Distance.Between(
                this.scene.player.x, this.scene.player.y,
                boss.x, boss.y
            ));
            boss.distanceText.setText(`${distance}m`);
            boss.distanceText.setPosition(indicatorX, indicatorY + 25);
            boss.distanceText.setVisible(true);
            
            // 添加"BOSS"文本提示
            if (!boss.bossIndicatorText) {
                boss.bossIndicatorText = this.scene.add.text(0, 0, 'BOSS', {
                    fontSize: '14px',
                    fontStyle: 'bold',
                    fill: '#ffffff',
                    stroke: '#ff0000',
                    strokeThickness: 3
                }).setOrigin(0.5)
                  .setScrollFactor(0)
                  .setDepth(10000);
            }
            
            boss.bossIndicatorText.setPosition(indicatorX, indicatorY - 25);
            boss.bossIndicatorText.setVisible(true);
            
        } else if (boss.indicator) {
            // 如果Boss在视口内，隐藏指示器
            boss.indicator.setVisible(false);
            if (boss.distanceText) {
                boss.distanceText.setVisible(false);
            }
            if (boss.bossIndicatorText) {
                boss.bossIndicatorText.setVisible(false);
            }
        }
    }

    bossAttack(boss) {
        const playerAngle = Phaser.Math.Angle.Between(
            boss.x, boss.y, this.scene.player.x, this.scene.player.y
        );

        switch (boss.attackPattern) {
            case 0: // 单发精准射击
                this.createEnemyBullet(boss.x, boss.y, playerAngle, 200, 25);
                break;

            case 1: // 扇形射击
                for (let i = -2; i <= 2; i++) {
                    this.createEnemyBullet(
                        boss.x, boss.y,
                        playerAngle + (i * 0.3),
                        180, 15
                    );
                }
                break;

            case 2: // 环形射击
                for (let i = 0; i < 8; i++) {
                    const angle = (Math.PI * 2 / 8) * i;
                    this.createEnemyBullet(boss.x, boss.y, angle, 150, 20);
                }
                break;
        }
    }

    createEnemyBullet(x, y, angle, speed, damage) {
        const bullet = this.scene.enemyBullets.create(x, y, 'enemy_bullet');
        bullet.setVelocity(
            Math.cos(angle) * speed,
            Math.sin(angle) * speed
        );
        bullet.damage = damage;
    }

    createEnemyHealthBar(enemy) {
        // 血条背景
        enemy.healthBarBg = this.scene.add.image(enemy.x - 10, enemy.y - 20, 'healthbar_bg');
        enemy.healthBarBg.setOrigin(0, 0.5);

        // 血条前景
        enemy.healthBar = this.scene.add.image(enemy.x - 10, enemy.y - 20, 'healthbar_fg');
        enemy.healthBar.setOrigin(0, 0.5);
    }

    createBossHealthBar(boss, wave) {
        // 获取相机视口的宽度和高度
        const camera = this.scene.cameras.main;
        const viewportWidth = camera.width;
        const viewportHeight = camera.height;
        
        // 计算血条位置 - 固定在视口中心顶部
        const centerX = viewportWidth / 2;
        const barWidth = Math.min(viewportWidth * 0.8, 500); // 血条宽度，根据视口宽度调整
        
        // 直接创建UI元素，不使用容器
        // Boss血条背景 - 更大更明显
        const bossHealthBg = this.scene.add.rectangle(centerX, 30, barWidth, 25, 0x000000, 0.8)
            .setScrollFactor(0)
            .setDepth(10000)
            .setOrigin(0.5, 0.5);
        bossHealthBg.setStrokeStyle(3, 0xffffff);
        
        // Boss血条前景 - 鲜红色
        const bossHealthFg = this.scene.add.rectangle(centerX, 30, barWidth, 20, 0xff0000)
            .setScrollFactor(0)
            .setDepth(10001)
            .setOrigin(0.5, 0.5);
            
        // Boss名称 - 更大更明显，确保wave参数有效
        const displayWave = wave || this.scene.wave || 5;
        const bossText = this.scene.add.text(centerX, 60, `BOSS - 波次 ${displayWave}`, {
            fontSize: '24px',
            fontStyle: 'bold',
            fill: '#ff0000',
            stroke: '#000000',
            strokeThickness: 4
        }).setOrigin(0.5)
          .setScrollFactor(0)
          .setDepth(10002);
        
        // 添加闪烁效果
        this.scene.tweens.add({
            targets: bossHealthBg,
            alpha: 0.6,
            duration: 500,
            yoyo: true,
            repeat: -1
        });
        
        // 存储引用
        boss.bossHealthBg = bossHealthBg;
        boss.bossHealthFg = bossHealthFg;
        boss.bossText = bossText;
        boss.wave = wave; // 存储波次信息
        
        // 确保Boss血条初始状态正确
        const healthPercent = boss.health / boss.maxHealth;
        boss.bossHealthFg.scaleX = healthPercent;
        
        // 添加警告文本
        const warningText = this.scene.add.text(centerX, 90, "BOSS来袭！", {
            fontSize: '20px',
            fontStyle: 'bold',
            fill: '#ffffff',
            stroke: '#ff0000',
            strokeThickness: 3
        }).setOrigin(0.5)
          .setScrollFactor(0)
          .setDepth(10002);
          
        // 添加警告闪烁效果
        this.scene.tweens.add({
            targets: warningText,
            alpha: 0.3,
            duration: 300,
            yoyo: true,
            repeat: 5,
            onComplete: () => {
                warningText.destroy();
            }
        });
        
        // 添加相机震动效果
        this.scene.cameras.main.shake(500, 0.01);
        
        // 创建Boss指示器纹理（如果不存在）
        if (!this.scene.textures.exists('boss_indicator')) {
            const indicatorGraphics = this.scene.add.graphics();
            indicatorGraphics.fillStyle(0xff0000, 1);
            indicatorGraphics.lineStyle(3, 0xffffff, 1);
            indicatorGraphics.beginPath();
            indicatorGraphics.moveTo(0, -20);
            indicatorGraphics.lineTo(15, 10);
            indicatorGraphics.lineTo(-15, 10);
            indicatorGraphics.closePath();
            indicatorGraphics.fillPath();
            indicatorGraphics.strokePath();
            
            // 将图形转换为纹理
            indicatorGraphics.generateTexture('boss_indicator', 30, 30);
            indicatorGraphics.destroy();
        }
        
        // 确保这些元素在视口中可见
    }

    // Boss弹幕攻击系统
    updateBossAttack(boss) {
        const currentTime = this.scene.time.now;

        // 检查是否可以攻击
        if (currentTime - boss.lastFired < boss.fireRate) {
            return;
        }

        // 根据Boss血量决定攻击模式
        const healthPercent = boss.health / boss.maxHealth;

        if (healthPercent > 0.7) {
            // 血量高时：单发精准射击
            this.bossSingleShot(boss);
        } else if (healthPercent > 0.4) {
            // 血量中等时：三连发
            this.bossTripleShot(boss);
        } else {
            // 血量低时：圆形弹幕
            this.bossCircularBarrage(boss);
        }

        boss.lastFired = currentTime;
    }

    // Boss单发攻击
    bossSingleShot(boss) {
        const angle = Phaser.Math.Angle.Between(
            boss.x, boss.y,
            this.scene.player.x, this.scene.player.y
        );

        this.createBossBullet(boss.x, boss.y, angle, boss.bulletSpeed, boss.damage);
    }

    // Boss三连发攻击
    bossTripleShot(boss) {
        const baseAngle = Phaser.Math.Angle.Between(
            boss.x, boss.y,
            this.scene.player.x, this.scene.player.y
        );

        // 三个方向：中间、左偏、右偏
        const angles = [baseAngle, baseAngle - 0.3, baseAngle + 0.3];

        angles.forEach((angle, index) => {
            this.scene.time.delayedCall(index * 100, () => {
                if (boss && boss.active) {
                    this.createBossBullet(boss.x, boss.y, angle, boss.bulletSpeed, boss.damage);
                }
            });
        });
    }

    // Boss圆形弹幕攻击
    bossCircularBarrage(boss) {
        const bulletCount = 12; // 12发子弹形成圆形
        const angleStep = (Math.PI * 2) / bulletCount;

        for (let i = 0; i < bulletCount; i++) {
            const angle = i * angleStep;
            this.scene.time.delayedCall(i * 50, () => {
                if (boss && boss.active) {
                    this.createBossBullet(boss.x, boss.y, angle, boss.bulletSpeed * 0.8, boss.damage * 0.7);
                }
            });
        }
    }

    // 创建Boss子弹
    createBossBullet(x, y, angle, speed, damage) {
        if (!this.scene.enemyBullets) return;

        const bullet = this.scene.enemyBullets.create(x, y, 'enemy_bullet');
        if (!bullet) return;

        bullet.setVelocity(
            Math.cos(angle) * speed,
            Math.sin(angle) * speed
        );

        bullet.damage = damage;
        bullet.setTint(0xff4444); // 红色子弹表示Boss攻击

        // Boss子弹稍大一些
        bullet.setScale(1.2);

        // 添加发光效果
        bullet.setBlendMode(Phaser.BlendModes.ADD);
    }
}